// 正式环境
// const requestURL = 'http://gpu.sslvip.net'
// 测试环境
const requestURL = 'http://191.126.8.93:18001'
// 'http://8.134.253.122:18001'
class HttpRequest {
	constructor() {
		// this.baseURL = ''
		this.baseURL = requestURL
	}
	
	tips(title) {
		uni.showToast({
			title,
			icon: 'none',
			mask: true
		})
	}
	
	toLogin() {
		uni.removeStorageSync('token');
		uni.removeStorageSync('userInfo');
		window.location.href = requestURL + '/h5/'
	}
	
	request(params) {
		const {
			url,
			method,
			data
		} = params
		
		let token = uni.getStorageSync('token')
		let header = {
			token
		}
		
		if(params.method == 'POST') {
			header['content-type'] = 'application/x-www-form-urlencoded'
		}

		const timeout = setTimeout(() => {
			uni.showLoading({
				title: "加载中..."
			})
		}, 800)

		// 发起网络请求
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.baseURL + url,
				method,
				header,
				data,
				success: res => {
					if (res.statusCode == 200) {
						const code = res.data.code
						if (code == 0) {
							resolve(res.data);
						} else {
							if(code === 3002) {
								uni.showModal({
									title: '提示',
									content: '当前登录状态已过期，请重新登录',
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											this.toLogin()
										}
									}
								});
							}else{
								const msg = res.data.msg || ''
								this.tips(msg)
								reject(res);
							}
						}
					} else {
						switch (res.statusCode) {
							case 401:
								uni.showModal({
									title: '提示',
									content: '当前登录状态已过期，请重新登录',
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											this.toLogin()
										}
									}
								});
								break;
							default:
								this.tips(res.msg || '请求错误')
								reject(res);
						}
					}
				},
				fail: e => {
					this.tips(e.errMsg)
					reject(e);
				},
				complete: () => {
					// 网络请求结束
					clearTimeout(timeout)
					uni.hideLoading();
					return;
				}
			})
		})
	}

	get(url, data) {
		return this.request({
			method: 'GET',
			url,
			data
		});
	}

	post(url, data) {
		return this.request({
			method: 'POST',
			url,
			data
		});
	}

	put(url, data) {
		return this.request({
			method: 'PUT',
			url,
			data
		});
	}

	delete(url, data) {
		return this.request({
			method: 'DELETE',
			url,
			data
		});
	}
}

export default new HttpRequest()